package com.yserp.kpyw.controller;
import com.jeecg.demo.entity.JfromOrderLineEntity;
import com.yserp.kpmd.entity.TKpChanpinEntity;
import com.yserp.kpmd.entity.TKpCusEntity;
import com.yserp.kpmd.entity.TKpGongdiEntity;
import com.yserp.kpmd.entity.TKpJiageEntity;
import com.yserp.kpyw.entity.TKpOrderEntity;
import com.yserp.kpyw.entity.TKpOrderOnejhEntity;
import com.yserp.kpyw.entity.TKpOrderjhEntity;
import com.yserp.kpyw.page.TKpOrderjhPage;
import com.yserp.kpyw.service.TKpOrderServiceI;
import com.yserp.kpyw.page.TKpOrderPage;
import com.yserp.kpyw.entity.TKpOrderOneEntity;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.*;
import java.text.SimpleDateFormat;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yserp.kpyw.service.TKpOrderjhServiceI;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.jeecgframework.core.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.jwt.util.GsonUtil;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import com.alibaba.fastjson.JSONArray;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;


/**   
 * @Title: Controller
 * @Description: 销售订单
 * @author onlineGenerator
 * @date 2018-07-17 23:57:06
 * @version V1.0   
 *
 */
@Api(value="TKpOrder",description="销售订单",tags="tKpOrderController")
@Controller
@RequestMapping("/tKpOrderController")
public class TKpOrderController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(TKpOrderController.class);

	@Autowired
	private TKpOrderServiceI tKpOrderService;
	@Autowired
	private TKpOrderjhServiceI tKpOrderjhService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;

	private String cusCode;
	private  String gdCode;
	/**
	 * 销售订单列表 页面跳转
	 * 
	 * @return
	 */



	@RequestMapping(params = "listjh")
	public ModelAndView listjh(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kpyw/tKpOrderjhList");
	}
	@RequestMapping(params = "listjhsh")
	public ModelAndView listshjh(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kpyw/tKpOrderjhshList");
	}
	@RequestMapping(params = "listjhsp")
	public ModelAndView listspjh(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kpyw/tKpOrderjhspList");
	}


	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kpyw/tKpOrderList");
	}

	@RequestMapping(params = "doPrint")
	public ModelAndView doPrint(String id,HttpServletRequest request) {
		TKpOrderEntity tKpOrder = tKpOrderService.getEntity(TKpOrderEntity.class, Integer.parseInt(id));
		tKpOrder.setOrStatus("已打印");
		systemService.updateEntitie(tKpOrder);
		request.setAttribute("tKpOrderPage", tKpOrder);
		request.setAttribute("kprq",DateUtils.date2Str(tKpOrder.getCreateDate(),DateUtils.date_sdf));
		//获取参数
		Object id0 = tKpOrder.getId();
		//===================================================================================
		//查询-产品
		String hql0 = "from TKpOrderOneEntity where 1 = 1 AND kP_ID = ? ";
		try {
			List<TKpOrderOneEntity> tKpOrderOneEntityList = systemService.findHql(hql0, id0);
			for(TKpOrderOneEntity t:tKpOrderOneEntityList){
				t.setOrStatus(tKpOrder.getOrStatus());
				systemService.updateEntitie(t);
			}
			request.setAttribute("tKpOrderOneList", tKpOrderOneEntityList);
		}catch (Exception e){

		}
		return new ModelAndView("com/yserp/kpyw/kporder-print");
	}


	@RequestMapping(params = "listdy")
	public ModelAndView listdy(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kpyw/tKpOrderdyList");
	}
	@RequestMapping(params = "listzj")
	public ModelAndView listzj(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kpyw/tKpOrderzjList");
	}

	@RequestMapping(params = "listcc")
	public ModelAndView listcc(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kpyw/tKpOrderccList");
	}


	@RequestMapping(params = "listkp")
	public ModelAndView listkp(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kpyw/tKpOrderkpList");
	}
	@RequestMapping(params = "listxh")
	public ModelAndView listxh(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kpyw/tKpOrderxhList");
	}

	@RequestMapping(params = "listsx")
	public ModelAndView listxhsp(HttpServletRequest request) {
		return new ModelAndView("com/yserp/kpyw/tKpOrdersxList");
	}
	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(String orStatus, String orderType, TKpOrderEntity tKpOrder,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TKpOrderEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tKpOrder);
		try{
		//自定义追加查询条件
			if(!StringUtil.isEmpty(orderType)){
				cq.eq("orderType",orderType);
			}
			if(!StringUtil.isEmpty(orStatus)){
				cq.eq("orStatus",orStatus);
			}
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.tKpOrderService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	@RequestMapping(params = "datagridkp")
	public void datagridkp(String orStatus, String orderType, TKpOrderEntity tKpOrder,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TKpOrderEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tKpOrder);
		try{
			//自定义追加查询条件
			if(!StringUtil.isEmpty(orderType)){
				cq.eq("orderType",orderType);
			}
			if(!StringUtil.isEmpty(orStatus)){
				cq.eq("orStatus",orStatus);
			}
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c = Calendar.getInstance();
			c.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(DateUtils.date2Str(DateUtils.date_sdf)));
			c.add(Calendar.DAY_OF_MONTH, 0);
			cq.ge("createDate", DateUtils.str2Date(sf.format(c.getTime()),DateUtils.date_sdf));
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.tKpOrderService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	@RequestMapping(params = "datagridjh")
	public void datagridjh(String orStatus, String orderType, TKpOrderjhEntity tKpOrder,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TKpOrderjhEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tKpOrder);
		try{
			//自定义追加查询条件
			if(!StringUtil.isEmpty(orderType)){
				cq.eq("orderType",orderType);
			}
			if(!StringUtil.isEmpty(orStatus)){
				cq.eq("orStatus",orStatus);
			}
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.tKpOrderjhService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	@ResponseBody
	public  String doAddcheck(String cus_code , String mat_qty ) {
		String message = "信贷充足";
		try{
			String sql = "SELECT  " +
					"    h.cus_code, " +
					"    (IFNULL((select " +
					"                    sum(ys_jine) " +
					"                from " +
					"                    t_kp_yushou " +
					"                where  "+
					"                    cus_code = h.cus_code " +
					"                        and ys_type in ('赊销','预收','退款')), " +
					"            0) + IFNULL((select  " +
					"                    sum(or_amount) " +
					"                from " +
					"                    t_kp_order_one " +
					"                where " +
					"                    cus_code = h.cus_code " +
					"                        and order_type = '损耗补偿'), " +
					"            0) - IFNULL((select " +
					"                    sum(or_amount)" +
					"                from" +
					"                    t_kp_order_one" +
					"                where" +
					"                    cus_code = h.cus_code" +
					"                        and order_type in ('正常销售' , '赊销销售'))," +
					"            0) - IFNULL((select  " +
					"                    cus_xindai " +
					"                from " +
					"                    t_kp_cus " +
					"                where " +
					"                    cus_code = h.cus_code),0)) as xindai " +
					"FROM " +
					"    t_kp_cus h " +
					"where " +" cus_code =   '"
					+ cus_code + "'" +
					"group by h.cus_code ";


			Map<String, Object> binMap	 = systemService.findOneForJdbc(sql);
			Double stock = Double.parseDouble(binMap.get("xindai").toString());
			Double mty = Double.parseDouble( mat_qty );
			mty = mty - 0.1;
			DecimalFormat df   = new DecimalFormat("######0.00");

			if(binMap!=null){
				if( stock < mty){

					message =   "信贷为"+df.format(stock);
				}
			}

//			tWzCkHeadService.addMain(tWzCkHead, tWzCkItemList);
//			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			message =  "信贷为0" ;
		}
		return message;
	}
	/**
	 * 删除销售订单
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(TKpOrderEntity tKpOrder, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		tKpOrder = systemService.getEntity(TKpOrderEntity.class, tKpOrder.getId());
		String message = "销售订单删除成功";
		try{
			tKpOrderService.delMain(tKpOrder);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "销售订单删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 批量删除销售订单
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		String message = "销售订单删除成功";
		try{
			for(String id:ids.split(",")){
				TKpOrderEntity tKpOrder = systemService.getEntity(TKpOrderEntity.class,
				Integer.parseInt(id)
				);
				tKpOrderService.delMain(tKpOrder);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "销售订单删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 添加销售订单
	 * 
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(TKpOrderEntity tKpOrder,TKpOrderPage tKpOrderPage, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String message = "添加成功";
		int fenshu = Integer.parseInt(tKpOrderPage.getKpFenshu());
		for (int i =0;i<fenshu;i++) {
			List<TKpOrderOneEntity> tKpOrderOneList =  tKpOrderPage.getTKpOrderOneList();

			try {
				TKpCusEntity cusEntity = systemService.findUniqueByProperty(TKpCusEntity.class, "cusCode", cusCode);
				if (cusEntity != null) {
					tKpOrder.setCusCode(cusCode);
					tKpOrder.setCusName(cusEntity.getCusName());
				}
				TKpGongdiEntity kpGongdiEntity = systemService.findUniqueByProperty(TKpGongdiEntity.class, "gdCode", gdCode);
				if (kpGongdiEntity != null) {
					tKpOrder.setGdCode(gdCode);
					tKpOrder.setGdName(kpGongdiEntity.getGdName());
				}
				List<TKpOrderOneEntity> tKpOrderOnenewList = new ArrayList<TKpOrderOneEntity>();
				Double sum = 0.00;
				DecimalFormat df = new DecimalFormat("######0.00");
				DecimalFormat df4 = new DecimalFormat("######0.00");
				for (TKpOrderOneEntity t : tKpOrderOneList) {
					if (StringUtil.isEmpty(t.getOrQty())) {
						continue;
					}

					try {
						if (Double.parseDouble(t.getOrQty()) <= 0) {
							continue;
						}
					} catch (Exception e) {

					}
					try {
						if (StringUtil.isEmpty(t.getBy1())) {
							Double fl = 0.00;
							fl = Double.parseDouble(t.getOrQty()) * Double.parseDouble(t.getCpTiji());
							t.setBy1(df4.format(fl));
						}
					} catch (Exception e) {

					}
					try {
						Double oramount = 0.00;
						//Double oramount =Double.parseDouble(t.getOrQty())*Double.parseDouble(t.getCpJiage());
						try {
							if (t.getCpJifei().equals("块") || t.getCpJifei().equals("车")) {
								oramount = Double.parseDouble(t.getOrQty()) * Double.parseDouble(t.getCpJiage());
							} else {
								oramount = Double.parseDouble(t.getBy1()) * Double.parseDouble(t.getCpJiage());
							}
						} catch (Exception e) {

						}
						;
						if (tKpOrder.getOrderType().equals("损耗补偿")) {
							t.setOrAmount(df.format(oramount));
						} else {
							t.setOrAmount(df.format(oramount));
						}
						sum = sum + oramount;
					} catch (Exception e) {

					}
					t.setOrderType(tKpOrder.getOrderType());
					t.setCusCode(cusCode);
					t.setGdCode(gdCode);
					t.setCusName(cusEntity.getCusName());
					t.setGdName(kpGongdiEntity.getGdName());
					t.setDocDate(DateUtils.getDate());
					tKpOrderOnenewList.add(t);

				}


				tKpOrder.setOrAmount(df.format(sum));
				tKpOrder.setOrStatus("已提交");
				try {
					if (tKpOrder.getOrderType().equals("正常销售")) {
						String messagel = doAddcheck(tKpOrder.getCusCode(), sum.toString());
						if (messagel.equals("信贷充足")) {
							tKpOrder.setOrStatus("已开票");
						} else {
							tKpOrder.setOrderType("赊销销售");
							tKpOrder.setOrRemark(tKpOrder.getOrRemark() + messagel);
						}
					}
				} catch (Exception e) {

				}
				tKpOrderOneList.clear();
				for (TKpOrderOneEntity t : tKpOrderOnenewList) {
					t.setOrStatus(tKpOrder.getOrStatus());
					t.setOrRemark(tKpOrder.getOrRemark());
					t.setCusType(tKpOrder.getBy5());
					tKpOrderOneList.add(t);
				}

				Map<String, Object> countMap = systemService
						.findOneForJdbc("SELECT max(by5) as count FROM t_kp_order  t where  date_format(t.create_date,'%Y-%m') = date_format(NOW(),'%Y-%m');");
				String noticeid = null;
				if (countMap != null) {
					String temp=null;
					try{
						temp = countMap.get("count").toString();

					}catch (Exception e){
						temp = "0000";
					}
					Long templ = Long.parseLong(temp.substring(temp.length() - 4, temp.length()));
					templ = templ + 1;
					noticeid = DateUtils.date2Str(new Date(), DateUtils.date_sdfyymm)
							+ StringUtil.leftPad(
							templ.intValue(), 4,
							'0');
				}
				tKpOrder.setBy5(noticeid);
				if (tKpOrder.getOrderType().equals("赊销销售")) {
					j.setSuccess(false);
					message = tKpOrder.getOrRemark();
				} else {
					TKpOrderEntity tKpOrder1 = new TKpOrderEntity();
					MyBeanUtils.copyBeanNotNull2Bean(tKpOrder, tKpOrder1);
					tKpOrder1.setId(null);
					List<TKpOrderOneEntity> tKpOrderOnesaveList = new ArrayList<TKpOrderOneEntity>();
					for(TKpOrderOneEntity t:tKpOrderOneList){
						TKpOrderOneEntity tnew = new TKpOrderOneEntity();
						MyBeanUtils.copyBeanNotNull2Bean(t, tnew);
						tnew.setId(null);
						tKpOrderOnesaveList.add(tnew);
					}
					tKpOrderService.addMain(tKpOrder1, tKpOrderOnesaveList);
					systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
				}

			} catch (Exception e) {
				e.printStackTrace();
				message = "销售订单添加失败";
				throw new BusinessException(e.getMessage());
			}
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 添加销售订单
	 *
	 * @return
	 */
	@RequestMapping(params = "doAddjh")
	@ResponseBody
	public AjaxJson doAddjh(TKpOrderjhEntity tKpOrder, TKpOrderjhPage tKpOrderPage, HttpServletRequest request) {
		List<TKpOrderOnejhEntity> tKpOrderOneList =  tKpOrderPage.getTKpOrderOneList();
		AjaxJson j = new AjaxJson();
		String message = "添加成功";
		try{
			TKpCusEntity cusEntity = systemService.findUniqueByProperty(TKpCusEntity.class,"cusCode",cusCode);
			if(cusEntity!=null){
				tKpOrder.setCusCode(cusCode);
				tKpOrder.setCusName(cusEntity.getCusName());
				tKpOrder.setBy5(cusEntity.getCusType());//客户类型
			}
			TKpGongdiEntity kpGongdiEntity = systemService.findUniqueByProperty(TKpGongdiEntity.class,"gdCode",gdCode);
			if(kpGongdiEntity!=null){
				tKpOrder.setGdCode(gdCode);
				tKpOrder.setGdName(kpGongdiEntity.getGdName()) ;
			}
			List<TKpOrderOnejhEntity> tKpOrderOnenewList = new ArrayList<TKpOrderOnejhEntity>();
			Double sum = 0.00;
			DecimalFormat df   = new DecimalFormat("######0.00");
			for(TKpOrderOnejhEntity t:tKpOrderOneList){
				if(StringUtil.isEmpty(t.getOrQty())){
					continue;
				}

				try{
					if(Double.parseDouble(t.getOrQty()) <=0){
						continue;
					}
				}catch (Exception e){

				}

				t.setOrderType(tKpOrder.getOrderType());
				t.setCusCode(cusCode);
				t.setGdCode(gdCode);
				t.setCusName(cusEntity.getCusName());
				t.setGdName(kpGongdiEntity.getGdName()) ;
				t.setDocDateb(DateUtils.str2Date(tKpOrder.getBy1(),DateUtils.date_sdf));
				t.setDocDatee(DateUtils.str2Date(tKpOrder.getBy2(),DateUtils.date_sdf));
				 t.setOrStatus("已提交");
				tKpOrderOnenewList.add(t);

			}
			tKpOrder.setOrStatus("已提交");
				tKpOrderjhService.addMain(tKpOrder, tKpOrderOnenewList);
				systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);


		}catch(Exception e){
			e.printStackTrace();
			message = "销售管控计划添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 更新销售订单
	 * 
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(TKpOrderEntity tKpOrder,TKpOrderPage tKpOrderPage, HttpServletRequest request) {
		List<TKpOrderOneEntity> tKpOrderOneList =  tKpOrderPage.getTKpOrderOneList();
		AjaxJson j = new AjaxJson();
		String message = "更新成功";
		try{
			tKpOrderService.updateMain(tKpOrder, tKpOrderOneList);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "更新销售订单失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	@RequestMapping(params = "doPrinte")
	@ResponseBody
	public void downReceiveExcel(String id,
								 HttpServletRequest request, HttpServletResponse response) {
		OutputStream fileOut = null;
		BufferedImage bufferImg = null;
		String codedFileName = null;
		TKpOrderEntity tKpOrder = systemService.getEntity(TKpOrderEntity.class,
				Integer.parseInt(id));// 获取抬头
		tKpOrder.setOrStatus("已打印");
		systemService.updateEntitie(tKpOrder);

		Object id0 = tKpOrder.getId();
		//===================================================================================
		//查询-产品
		String hql0 = "from TKpOrderOneEntity where 1 = 1 AND kpId = ? ";

			List<TKpOrderOneEntity> tKpOrderOneEntityList = systemService.findHql(hql0, id0.toString());
			for(TKpOrderOneEntity t:tKpOrderOneEntityList){
				t.setOrStatus(tKpOrder.getOrStatus());
				systemService.updateEntitie(t);
			}


		try {
			// 进行转码，使其支持中文文件名
			codedFileName = java.net.URLEncoder.encode("中文", "UTF-8");
			response.setHeader("content-disposition", "attachment;filename="
					+ id + ".xls");

			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet = wb.createSheet(tKpOrder.getOrderType());
			StringBuffer sber = new StringBuffer();

			ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();

//			bufferImg = ImageIO.read(BarcodeUtil.generateToStream(wmImNoticeH
//					.getNoticeId()));
			bufferImg = QRcodeUtil.createImage(tKpOrder.getId().toString());
			ImageIO.write(bufferImg, "jpg", byteArrayOut);

			// 画图的顶级管理器，一个sheet只能获取一个（一定要注意这点）
			HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
			// anchor主要用于设置图片的属性
			HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0,
					(short) 5, 0, (short) 6, 3);
			anchor.setAnchorType(2);
			// 插入图片
			patriarch
					.createPicture(anchor, wb.addPicture(
							byteArrayOut.toByteArray(),
							HSSFWorkbook.PICTURE_TYPE_JPEG));



			sheet.setMargin(HSSFSheet.TopMargin,0.1);// 页边距（上）
			sheet.setMargin(HSSFSheet.BottomMargin,0.1);// 页边距（下）
			sheet.setMargin(HSSFSheet.LeftMargin,0.8);// 页边距（左）
			sheet.setMargin(HSSFSheet.RightMargin,0.0);// 页边距（右

			sheet.setColumnWidth(0, 19 * 200);
			sheet.setColumnWidth(1, 24 * 200);
			sheet.setColumnWidth(2, 8 * 200);
			sheet.setColumnWidth(3, 15 * 200);
			sheet.setColumnWidth(4, 15 * 200);
			sheet.setColumnWidth(5, 18 * 200);
			sheet.setColumnWidth(6, 12 * 200);
			sheet.setColumnWidth(7, 1 * 200);
			// sheet.setColumnWidth(6, 8 * 256);
			// sheet.setColumnWidth(7, 8 * 256);
			// sheet.setColumnWidth(8, 8 * 256);
			// 创建第一行
			Row row = sheet.createRow((short) 0); // 第一行空白

			// 创建两种单元格格式
			CellStyle cs = wb.createCellStyle();
			CellStyle cs2 = wb.createCellStyle();
			CellStyle cs3 = wb.createCellStyle();
			CellStyle cs4 = wb.createCellStyle();
			CellStyle cs5 = wb.createCellStyle();
			// 创建两种字体
			Font f = wb.createFont();
			Font f2 = wb.createFont();

			// 创建第一种字体样式（用于列名）
			f.setFontHeightInPoints((short) 14);
			f.setColor(IndexedColors.BLACK.getIndex());
			f.setBoldweight(Font.BOLDWEIGHT_BOLD);

			// 创建第二种字体样式（用于值）
			f2.setFontHeightInPoints((short) 12);
			f2.setColor(IndexedColors.BLACK.getIndex());

			// Font f3=wb.createFont();
			// f3.setFontHeightInPoints((short) 10);
			// f3.setColor(IndexedColors.RED.getIndex());

			// 设置第一种单元格的样式（用于列名）
			cs.setFont(f);
			cs.setBorderLeft(CellStyle.BORDER_NONE);
			cs.setBorderRight(CellStyle.BORDER_NONE);
			cs.setBorderTop(CellStyle.BORDER_NONE);
			cs.setBorderBottom(CellStyle.BORDER_NONE);
			cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			// 设置第二种单元格的样式（用于值）
			cs2.setFont(f2);
			cs2.setBorderLeft(CellStyle.BORDER_NONE);
			cs2.setBorderRight(CellStyle.BORDER_NONE);
			cs2.setBorderTop(CellStyle.BORDER_NONE);
			cs2.setBorderBottom(CellStyle.BORDER_NONE);
			cs2.setWrapText(true);

			// cs2.setAlignment(CellStyle.BORDER_NONE);

			cs3.setFont(f2);
			cs3.setBorderLeft(CellStyle.BORDER_MEDIUM);
			cs3.setBorderRight(CellStyle.BORDER_MEDIUM);
			cs3.setBorderTop(CellStyle.BORDER_MEDIUM);
			cs3.setBorderBottom(CellStyle.BORDER_MEDIUM);
			cs3.setAlignment(CellStyle.ALIGN_CENTER);
			cs4.setFont(f2);
			cs4.setBorderTop(CellStyle.BORDER_MEDIUM);
			cs4.setBorderBottom(CellStyle.BORDER_MEDIUM);

			cs5.setFont(f2);
			cs5.setBorderLeft(CellStyle.BORDER_NONE);
			cs5.setBorderRight(CellStyle.BORDER_NONE);
			cs5.setBorderTop(CellStyle.BORDER_NONE);
			cs5.setBorderBottom(CellStyle.BORDER_NONE);
//			cs5.setWrapText(true);

			Row row1 = sheet.createRow((short) 1); // 第一行标题
			row1.setHeight((short) 600);
			Cell cellTitle = row1.createCell(0);
			cellTitle.setCellValue(ResourceUtil.getConfigByName("comname"));
			cellTitle.setCellStyle(cs);

			Cell cellHead12 = row1.createCell(3);
			cellHead12.setCellValue("日期："+DateUtils.date2Str(tKpOrder.getCreateDate(),DateUtils.date_sdf));
			cellHead12.setCellStyle(cs2);

			Row row2 = sheet.createRow((short) 2); // 第二行标题
			row2.setHeight((short) 600);
			Cell cellTitle2 = row2.createCell(0);
			cellTitle2.setCellValue("光厦牌粉煤灰产品销售单");
			cellTitle2.setCellStyle(cs);

			Cell cellHead11 = row2.createCell(3);
			cellHead11.setCellValue("NO：" + tKpOrder.getId());
			cellHead11.setCellStyle(cs2);

			Row rowHead1 = sheet.createRow((short) 3); // 头部第三行
			rowHead1.setHeight((short) 600);
			Cell cellHead31 = rowHead1.createCell(0);
			cellHead31.setCellValue("客户：" +tKpOrder.getCusName());
			cellHead31.setCellStyle(cs2);
			Cell cellHead23 = rowHead1.createCell(3);
			cellHead23.setCellValue("工地："+tKpOrder.getGdName());
			cellHead23.setCellStyle(cs2);



			// 合并单元格
			CellRangeAddress c0 = new CellRangeAddress(0, 0, 0, 7); // 第一行空白
			CellRangeAddress c1 = new CellRangeAddress(1, 1, 0, 2);// 第一行标题
			CellRangeAddress c12 = new CellRangeAddress(1, 1, 3, 4);// 第一行  客户送货时间

			CellRangeAddress c2 = new CellRangeAddress(2, 2, 0, 2);// 第二行标题
			CellRangeAddress c22 = new CellRangeAddress(2, 2, 3, 4);// 第二行通知单号

			CellRangeAddress c31 = new CellRangeAddress(3, 3, 0, 2);// 第三行通知单号
			CellRangeAddress c32 = new CellRangeAddress(3, 3, 3, 6);// 第三行通知单号
//			CellRangeAddress c33 = new CellRangeAddress(3, 3, 5, 5);// 第四行客户
//			CellRangeAddress c34 = new CellRangeAddress(3, 3, 6, 7);// 第四行客户送货时间
//			CellRangeAddress c4 = new CellRangeAddress(4, 4, 0, 1);// 第五行客户
//			CellRangeAddress c5 = new CellRangeAddress(4, 4, 2, 6);// 第五行客户送货时间
			// CellRangeAddress c4 = new CellRangeAddress(4, 4, 0, 1);
			// CellRangeAddress c5 = new CellRangeAddress(4, 4, 2, 3);
			// CellRangeAddress c6 = new CellRangeAddress(4, 4, 4, 5);
			// CellRangeAddress c7 = new CellRangeAddress(4, 4, 6, 6);

			sheet.addMergedRegion(c0);
			sheet.addMergedRegion(c1);
			sheet.addMergedRegion(c12);
			sheet.addMergedRegion(c2);
			sheet.addMergedRegion(c22);
			sheet.addMergedRegion(c31);
			sheet.addMergedRegion(c32);
//			sheet.addMergedRegion(c4);
//			sheet.addMergedRegion(c5);
//			sheet.addMergedRegion(c33);
//			sheet.addMergedRegion(c34);
			// sheet.addMergedRegion(c7);

			Row rowColumnName = sheet.createRow((short) 4); // 列名
			rowColumnName.setHeight((short) 500);
			String[] columnNames = { "产品名称", "规格", "单位", "数量", "m³",
					"等级" ,"备注"};

			for (int i = 0; i < columnNames.length; i++) {
				Cell cell = rowColumnName.createCell(i);
				cell.setCellValue(columnNames[i]);
				cell.setCellStyle(cs3);
			}
			int cellsNum = 4;
			int cerconNo = 1;
			for (TKpOrderOneEntity t:tKpOrderOneEntityList) {
				cellsNum++;
				Row rowColumnValue = sheet.createRow((short) cellsNum); // 列名
				rowColumnValue.setHeight((short) 500);
				Cell cell1 = rowColumnValue.createCell(0);
				try {
					cell1.setCellStyle(cs3);
					cell1.setCellValue(t.getCpName());
				}catch (Exception e){

				}

				Cell cell2 = rowColumnValue.createCell(1);


				try {
					cell2.setCellStyle(cs3);
					cell2.setCellValue(t.getCpGuige());
				}catch (Exception e){

				}
				try {
					Cell cell3 = rowColumnValue.createCell(2);
					cell3.setCellValue(t.getCpJifei());
					cell3.setCellStyle(cs3);
				}catch (Exception e){

				}
				try {
					Cell cell4 = rowColumnValue.createCell(3);
					cell4.setCellValue(t.getOrQty());
					cell4.setCellStyle(cs3);
				}catch (Exception e){

				}
			try {
					Cell cell7 = rowColumnValue.createCell(4);
					cell7.setCellValue(t.getBy1());
					cell7.setCellStyle(cs3);
				}catch (Exception e){

				}
				try {
					Cell cell8 = rowColumnValue.createCell(5);
					cell8.setCellValue(t.getCpDengji());
					cell8.setCellStyle(cs3);
				}catch (Exception e){

				}
				try {
					Cell cell8 = rowColumnValue.createCell(6);
					cell8.setCellValue("");
					cell8.setCellStyle(cs3);
				}catch (Exception e){

				}
				cerconNo++;
			}
			int rr  = 1 + cellsNum;
			Row rowColumnInfo1 = sheet.createRow((short) 1 + cellsNum); // 列名
			rowColumnInfo1.setHeight((short) 500);
			Cell cellrow0 = rowColumnInfo1.createCell(0);
			cellrow0.setCellValue("承运人");
			cellrow0.setCellStyle(cs3);
			Cell cellrow1 = rowColumnInfo1.createCell(1);
			cellrow1.setCellValue("");
			cellrow1.setCellStyle(cs3);
			Cell cellrow2 = rowColumnInfo1.createCell(2);
			cellrow2.setCellValue("车号");
			cellrow2.setCellStyle(cs3);
			Cell cellrow3 = rowColumnInfo1.createCell(3);
			cellrow3.setCellValue("");
			cellrow3.setCellStyle(cs3);

			Cell cellrow4 = rowColumnInfo1.createCell(4);
			cellrow4.setCellValue("收货人签字");
			cellrow4.setCellStyle(cs3);
			Cell cellrow5 = rowColumnInfo1.createCell(5);
			cellrow5.setCellValue("");
			cellrow5.setCellStyle(cs3);
			Cell cellrow6 = rowColumnInfo1.createCell(6);
			cellrow6.setCellValue("");
			cellrow6.setCellStyle(cs3);

//			CellRangeAddress rr2 = new CellRangeAddress(rr, rr, 3, 4);// 第四行客户
			CellRangeAddress rr3 = new CellRangeAddress(rr, rr, 5, 6);// 第四行客户送货时间
//			CellRangeAddress c4 = new CellRangeAddress(4, 4, 0, 1);// 第五行客户
//			CellRangeAddress c5 = new CellRangeAddress(4, 4, 2, 6);// 第五行客户送货时间
			// CellRangeAddress c4 = new CellRangeAddress(4, 4, 0, 1);
			// CellRangeAddress c5 = new CellRangeAddress(4, 4, 2, 3);
			// CellRangeAddress c6 = new CellRangeAddress(4, 4, 4, 5);
			// CellRangeAddress c7 = new CellRangeAddress(4, 4, 6, 6);

//			sheet.addMergedRegion(rr2);
			sheet.addMergedRegion(rr3);

			Row rowColumnInfo = sheet.createRow((short) 2 + cellsNum); // 列名
			Cell cellrow = rowColumnInfo.createCell(0);
			cellrow.setCellValue("主管：             制单： "+ResourceUtil.getSessionUser().getRealName()+"             收货人：               验收：                 ");
			cellrow.setCellStyle(cs5);
//			rowColumnInfo.createCell(0).setCellValue(
//					"领用人：                       仓管：                     主管：                      ");
//			CellRangeAddress c15 = new CellRangeAddress(10 + cellsNum,
//					10 + cellsNum, 0, 6);
//			sheet.addMergedRegion(c15);
			fileOut = response.getOutputStream();
			HSSFPrintSetup printSetup = sheet.getPrintSetup();
			printSetup.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
			printSetup.setLandscape(false);
			wb.write(fileOut);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fileOut != null) {
				try {
					fileOut.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}





	/**
	 * 删除销售订单
	 *
	 * @return
	 */
	@RequestMapping(params = "setvalue")
	@ResponseBody
	public AjaxJson setvalue(String LcusCode,String LgdCode, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		cusCode = LcusCode;
		gdCode = LgdCode;
		return j;
	}


	/**
	 * 删除销售订单
	 *
	 * @return
	 */
	@RequestMapping(params = "doUpdatesp")
	@ResponseBody
	public AjaxJson doUpdatesp(String orStatus,String id, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		TKpOrderEntity tKpOrder = systemService.getEntity(TKpOrderEntity.class, Integer.parseInt(id));
		String message = "成功";
		try{
			tKpOrder.setOrStatus(orStatus);
			tKpOrderService.updateEntitie(tKpOrder);
			//获取参数
			Object id0 = tKpOrder.getId();
			//===================================================================================
			//查询-产品
			String hql0 = "from TKpOrderOneEntity where 1 = 1 AND kpId = ? ";
			try {
				List<TKpOrderOneEntity> tKpOrderOneEntityList = systemService.findHql(hql0, id0.toString());
				for(TKpOrderOneEntity t:tKpOrderOneEntityList){
					try{
						if("已开票".equals(orStatus)){
							t.setBpmStatus("3");
						}
					}catch (Exception e){
					}
					t.setOrStatus(orStatus);
					systemService.updateEntitie(t);
				}
			}catch (Exception e){

			}
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 删除销售订单
	 *
	 * @return
	 */
	@RequestMapping(params = "doUpdatejhsp")
	@ResponseBody
	public AjaxJson doUpdatejhsp(String orStatus,String id, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		TKpOrderjhEntity tKpOrder = systemService.getEntity(TKpOrderjhEntity.class, Integer.parseInt(id));
		String message = "成功";
		try{
			tKpOrder.setOrStatus(orStatus);
			tKpOrderjhService.updateEntitie(tKpOrder);
			//获取参数
			Object id0 = tKpOrder.getId();
			//===================================================================================
			//查询-产品
			String hql0 = "from TKpOrderOnejhEntity where 1 = 1 AND kpId = ? ";
			try {
				List<TKpOrderOnejhEntity> tKpOrderOneEntityList = systemService.findHql(hql0, id0.toString());
				for(TKpOrderOnejhEntity t:tKpOrderOneEntityList){
					t.setOrStatus(orStatus);
					systemService.updateEntitie(t);
				}
			}catch (Exception e){

			}
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 销售订单新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(String orderType,TKpOrderEntity tKpOrder, HttpServletRequest req) {
//		cusCode ;
//		gdCode;
		if (StringUtil.isNotEmpty(tKpOrder.getId())) {
			tKpOrder = tKpOrderService.getEntity(TKpOrderEntity.class, tKpOrder.getId());
			req.setAttribute("tKpOrderPage", tKpOrder);
		}
		req.setAttribute("cusCode", cusCode);
		req.setAttribute("gdCode", gdCode);
//		tKpOrder.setCusCode(cusCode);
//		tKpOrder.setGdCode(gdCode);
		req.setAttribute("orderType",orderType);

		return new ModelAndView("com/yserp/kpyw/tKpOrder-add");
	}
	/**
	 * 销售订单新增页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "goAddjh")
	public ModelAndView goAddjh(String orderType,TKpOrderjhEntity tKpOrder, HttpServletRequest req) {
//		cusCode ;
//		gdCode;
		if (StringUtil.isNotEmpty(tKpOrder.getId())) {
			tKpOrder = tKpOrderjhService.getEntity(TKpOrderjhEntity.class, tKpOrder.getId());
			req.setAttribute("tKpOrderPage", tKpOrder);
		}
		req.setAttribute("cusCode", cusCode);
		req.setAttribute("gdCode", gdCode);
//		tKpOrder.setCusCode(cusCode);
//		tKpOrder.setGdCode(gdCode);
		req.setAttribute("orderType",orderType);

		return new ModelAndView("com/yserp/kpyw/tKpOrderjh-add");
	}
	/**
	 * 销售订单编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(TKpOrderEntity tKpOrder, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tKpOrder.getId())) {
			tKpOrder = tKpOrderService.getEntity(TKpOrderEntity.class, tKpOrder.getId());
			req.setAttribute("tKpOrderPage", tKpOrder);
		}
		return new ModelAndView("com/yserp/kpyw/tKpOrder-update");
	}
	@RequestMapping(params = "goUpdatejh")
	public ModelAndView goUpdatejh(TKpOrderjhEntity tKpOrder, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tKpOrder.getId())) {
			tKpOrder = tKpOrderjhService.getEntity(TKpOrderjhEntity.class, tKpOrder.getId());
			req.setAttribute("tKpOrderPage", tKpOrder);
		}
		return new ModelAndView("com/yserp/kpyw/tKpOrderjh-update");
	}

	@RequestMapping(params = "jfromOrderLineDatagrid")
	public void jfromOrderLineDatagrid(TKpOrderOneEntity tKpOrderOneEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TKpOrderOneEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tKpOrderOneEntity);
		cq.add();
		this.tKpOrderService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}


	/**
	 * 加载明细列表[产品]
	 *
	 * @return
	 */
	@RequestMapping(params = "tKpOrderOnefList")
	public ModelAndView tKpOrderOnefList(TKpOrderEntity tKpOrder, HttpServletRequest req) {
		System.out.print("&&&&&&&&&&&&&&&&"+cusCode);
		//===================================================================================
		//获取参数
		Object id0 = tKpOrder.getId();
		//===================================================================================
		//查询-产品
		String hql0 = "from TKpJiageEntity where cpJiage > 0 and bpmStatus = ? AND cusCode = ? and gdCode = ? ";
		try{
			List<TKpJiageEntity> tKpJiageEntityList = systemService.findHql(hql0,"3",cusCode,gdCode);

			List<TKpOrderOneEntity> tKpOrderOneEntityList = new ArrayList<TKpOrderOneEntity>();
			for(TKpJiageEntity t: tKpJiageEntityList){
				TKpOrderOneEntity  t1 =  new TKpOrderOneEntity();
				t1.setOrQty("0");
				t1.setCpCode(t.getCpCode());
				t1.setCpName(t.getCpName());
				t1.setCpGuige(t.getBy2());
				t1.setCpDengji(t.getBy3());
				t1.setCpJifei(t.getBy4());
				t1.setCpJiage(t.getCpJiage());
				TKpChanpinEntity chanpin = systemService.findUniqueByProperty(TKpChanpinEntity.class,"cpCode",t.getCpCode());
				t1.setCpTiji(chanpin.getCpTiji());
				TKpCusEntity cusEntity = systemService.findUniqueByProperty(TKpCusEntity.class,"cusCode",t.getCusCode());
				if(cusEntity==null){
					continue;
				}
				TKpGongdiEntity kpGongdiEntity = systemService.findUniqueByProperty(TKpGongdiEntity.class,"gdCode",t.getGdCode());
				if(kpGongdiEntity==null){
					continue;
				}else {
					if(kpGongdiEntity.getBy2().equals("完工")){
						continue;
					}
				}
				tKpOrderOneEntityList.add(t1);
			}
			req.setAttribute("tKpOrderOneList", tKpOrderOneEntityList);
		}catch(Exception e){
			logger.info(e.getMessage());
		}

		return new ModelAndView("com/yserp/kpyw/tKpOrderOneList");
	}


	/**
	 * 加载明细列表[产品]
	 *
	 * @return
	 */
	@RequestMapping(params = "tKpOrderOnejhfList")
	public ModelAndView tKpOrderOnejhfList(TKpOrderjhEntity tKpOrder, HttpServletRequest req) {
		System.out.print("&&&&&&&&&&&&&&&&"+cusCode);
		//===================================================================================
		//获取参数
		Object id0 = tKpOrder.getId();
		//===================================================================================
		//查询-产品
		String hql0 = "from TKpJiageEntity where bpmStatus = ? AND cusCode = ? and gdCode = ? ";
		try{
			List<TKpJiageEntity> tKpJiageEntityList = systemService.findHql(hql0,"3",cusCode,gdCode);

			List<TKpOrderOnejhEntity> tKpOrderOneEntityList = new ArrayList<TKpOrderOnejhEntity>();
			for(TKpJiageEntity t: tKpJiageEntityList){
				TKpOrderOnejhEntity  t1 =  new TKpOrderOnejhEntity();
				t1.setOrQty("0");
				t1.setCpCode(t.getCpCode());
				t1.setCpName(t.getCpName());
				t1.setCpGuige(t.getBy2());
				t1.setCpDengji(t.getBy3());
				t1.setCpJifei(t.getBy4());
				t1.setCpJiage(t.getCpJiage());
				TKpChanpinEntity chanpin = systemService.findUniqueByProperty(TKpChanpinEntity.class,"cpCode",t.getCpCode());
				t1.setCpTiji(chanpin.getCpTiji());
				tKpOrderOneEntityList.add(t1);
			}

			req.setAttribute("tKpOrderOneList", tKpOrderOneEntityList);
		}catch(Exception e){
			logger.info(e.getMessage());
		}
		return new ModelAndView("com/yserp/kpyw/tKpOrderOnejhList");
	}

	/**
	 * 加载明细列表[产品]
	 * 
	 * @return
	 */
	@RequestMapping(params = "tKpOrderOneList")
	public ModelAndView tKpOrderOneList(TKpOrderEntity tKpOrder, HttpServletRequest req) {
		//===================================================================================
		//获取参数
		Object id0 = tKpOrder.getId();
		//===================================================================================
		//查询-产品
	    String hql0 = "from TKpOrderOneEntity where 1 = 1 AND kP_ID = ? ";
	    try{
	    	List<TKpOrderOneEntity> tKpOrderOneEntityList = systemService.findHql(hql0,id0);
			req.setAttribute("tKpOrderOneList", tKpOrderOneEntityList);
		}catch(Exception e){
			logger.info(e.getMessage());
		}
		return new ModelAndView("com/yserp/kpyw/tKpOrderOneList");
	}
	/**
	 * 加载明细列表[产品]
	 *
	 * @return
	 */
	@RequestMapping(params = "tKpOrderOnejhList")
	public ModelAndView tKpOrderOnejhList(TKpOrderjhEntity tKpOrder, HttpServletRequest req) {
		//===================================================================================
		//获取参数
		Object id0 = tKpOrder.getId();
		//===================================================================================
		//查询-产品
		String hql0 = "from TKpOrderOnejhEntity where 1 = 1 AND kP_ID = ? ";
		try{
			List<TKpOrderOnejhEntity> tKpOrderOneEntityList = systemService.findHql(hql0,id0);
			req.setAttribute("tKpOrderOneList", tKpOrderOneEntityList);
		}catch(Exception e){
			logger.info(e.getMessage());
		}
		return new ModelAndView("com/yserp/kpyw/tKpOrderOnejhList");
	}
    /**
    * 导出excel
    *
    * @param request
    * @param response
    */
    @RequestMapping(params = "exportXls")
    public String exportXls(TKpOrderEntity tKpOrder,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid,ModelMap map) {
    	CriteriaQuery cq = new CriteriaQuery(TKpOrderEntity.class, dataGrid);
    	//查询条件组装器
    	org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tKpOrder);
    	try{
    	//自定义追加查询条件
    	}catch (Exception e) {
    		throw new BusinessException(e.getMessage());
    	}
    	cq.add();
    	List<TKpOrderEntity> list=this.tKpOrderService.getListByCriteriaQuery(cq, false);
    	List<TKpOrderPage> pageList=new ArrayList<TKpOrderPage>();
        if(list!=null&&list.size()>0){
        	for(TKpOrderEntity entity:list){
        		try{
        		TKpOrderPage page=new TKpOrderPage();
        		   MyBeanUtils.copyBeanNotNull2Bean(entity,page);
            	    Object id0 = entity.getId();
				    String hql0 = "from TKpOrderOneEntity where 1 = 1 AND kP_ID = ? ";
        	        List<TKpOrderOneEntity> tKpOrderOneEntityList = systemService.findHql(hql0,id0);
            		page.setTKpOrderOneList(tKpOrderOneEntityList);
            		pageList.add(page);
            	}catch(Exception e){
            		logger.info(e.getMessage());
            	}
            }
        }
        map.put(NormalExcelConstants.FILE_NAME,"销售订单");
        map.put(NormalExcelConstants.CLASS,TKpOrderPage.class);
        map.put(NormalExcelConstants.PARAMS,new ExportParams("销售订单列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
            "导出信息"));
        map.put(NormalExcelConstants.DATA_LIST,pageList);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

    /**
	 * 通过excel导入数据
	 * @param request
	 * @param
	 * @return
	 */
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(2);
			params.setNeedSave(true);
			try {
				List<TKpOrderPage> list =  ExcelImportUtil.importExcel(file.getInputStream(), TKpOrderPage.class, params);
				TKpOrderEntity entity1=null;
				for (TKpOrderPage page : list) {
					entity1=new TKpOrderEntity();
					MyBeanUtils.copyBeanNotNull2Bean(page,entity1);
		            tKpOrderService.addMain(entity1, page.getTKpOrderOneList());
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			}
			return j;
	}
	/**
	* 导出excel 使模板
	*/
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(ModelMap map) {
		map.put(NormalExcelConstants.FILE_NAME,"销售订单");
		map.put(NormalExcelConstants.CLASS,TKpOrderPage.class);
		map.put(NormalExcelConstants.PARAMS,new ExportParams("销售订单列表", "导出人:"+ ResourceUtil.getSessionUser().getRealName(),
		"导出信息"));
		map.put(NormalExcelConstants.DATA_LIST,new ArrayList());
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	* 导入功能跳转
	*
	* @return
	*/
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name", "tKpOrderController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}

 	
 	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="销售订单列表信息",produces="application/json",httpMethod="GET")
	public ResponseMessage<List<TKpOrderPage>> list() {
		List<TKpOrderEntity> list= tKpOrderService.getList(TKpOrderEntity.class);
    	List<TKpOrderPage> pageList=new ArrayList<TKpOrderPage>();
        if(list!=null&&list.size()>0){
        	for(TKpOrderEntity entity:list){
        		try{
        			TKpOrderPage page=new TKpOrderPage();
        		   MyBeanUtils.copyBeanNotNull2Bean(entity,page);
					Object id0 = entity.getId();
				     String hql0 = "from TKpOrderOneEntity where 1 = 1 AND kP_ID = ? ";
	    			List<TKpOrderOneEntity> tKpOrderOneOldList = this.tKpOrderService.findHql(hql0,id0);
            		page.setTKpOrderOneList(tKpOrderOneOldList);
            		pageList.add(page);
            	}catch(Exception e){
            		logger.info(e.getMessage());
            	}
            }
        }
		return Result.success(pageList);
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据ID获取销售订单信息",notes="根据ID获取销售订单信息",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> get(@ApiParam(required=true,name="id",value="ID")@PathVariable("id") String id) {
		TKpOrderEntity task = tKpOrderService.get(TKpOrderEntity.class, id);
		if (task == null) {
			return Result.error("根据ID获取销售订单信息为空");
		}
		TKpOrderPage page = new TKpOrderPage();
		try {
			MyBeanUtils.copyBeanNotNull2Bean(task, page);
				Object id0 = task.getId();
		    String hql0 = "from TKpOrderOneEntity where 1 = 1 AND kP_ID = ? ";
			List<TKpOrderOneEntity> tKpOrderOneOldList = this.tKpOrderService.findHql(hql0,id0);
    		page.setTKpOrderOneList(tKpOrderOneOldList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result.success(page);
	}
 	
 	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="创建销售订单")
	public ResponseMessage<?> create(@ApiParam(name="销售订单对象")@RequestBody TKpOrderPage tKpOrderPage, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<TKpOrderPage>> failures = validator.validate(tKpOrderPage);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		//保存
		List<TKpOrderOneEntity> tKpOrderOneList =  tKpOrderPage.getTKpOrderOneList();
		
		TKpOrderEntity tKpOrder = new TKpOrderEntity();
		try{
			MyBeanUtils.copyBeanNotNull2Bean(tKpOrderPage,tKpOrder);
		}catch(Exception e){
            logger.info(e.getMessage());
            return Result.error("保存销售订单失败");
        }
		tKpOrderService.addMain(tKpOrder, tKpOrderOneList);

		return Result.success(tKpOrder);
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="更新销售订单",notes="更新销售订单")
	public ResponseMessage<?> update(@RequestBody TKpOrderPage tKpOrderPage) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<TKpOrderPage>> failures = validator.validate(tKpOrderPage);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		//保存
		List<TKpOrderOneEntity> tKpOrderOneList =  tKpOrderPage.getTKpOrderOneList();
		
		TKpOrderEntity tKpOrder = new TKpOrderEntity();
		try{
			MyBeanUtils.copyBeanNotNull2Bean(tKpOrderPage,tKpOrder);
		}catch(Exception e){
            logger.info(e.getMessage());
            return Result.error("销售订单更新失败");
        }
		tKpOrderService.updateMain(tKpOrder, tKpOrderOneList);

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return Result.success();
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	@ApiOperation(value="删除销售订单")
	public ResponseMessage<?> delete(@ApiParam(name="id",value="ID",required=true)@PathVariable("id") String id) {
		logger.info("delete[{}]" + id);
		// 验证
		if (StringUtils.isEmpty(id)) {
			return Result.error("ID不能为空");
		}
		try {
			TKpOrderEntity tKpOrder = tKpOrderService.get(TKpOrderEntity.class, id);
			tKpOrderService.delMain(tKpOrder);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("销售订单删除失败");
		}

		return Result.success();
	}
}
